import router from '@/router/index'

import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'
Nprogress.configure({ showSpinner: false }) // 进度条右侧的转圈效果去除
import pinia from '@/store'
import useUserStore from '@/store/modules/user'
const userStore = useUserStore(pinia)
import setting from '@/setting'

router.beforeEach(async (to: any, from: any, next: any) => {
  Nprogress.start()
  const token = userStore.token
  const username = userStore.username
  const toPath = to.path
  const redirectQuery = {
    redirect: toPath
  }
  if (token) {
    if (toPath === '/login') {
      next('/')
    } else {
      if (username) {
        next()
      } else {
        try {
          await userStore.userInfo()
          
          next({...to})
        } catch (e) {
          // 获取用户信息失效、token过期、手动修改token
          //  return Promise.reject(e)
          await userStore.userLogout()
          next({
            path: '/login',
            query: redirectQuery
          })
        }
      }
    }
  } else {
    if (toPath === '/login') {
      next()
    } else {
      next({
        path: '/login',
        query: redirectQuery
      })
    }
  }
})

router.afterEach((to: any) => {
  Nprogress.done()
  document.title = setting.title + ' - ' + to.meta.title
})
